package com.cong.clause.service;

import com.cong.clause.mapper.ClauseMapper;
import com.cong.clause.pojo.Clause;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * @author cong
 * <p>
 * created on 2021/4/16 下午8:31
 */
@Service
public class ClauseService {

    @Autowired
    private ClauseMapper clauseMapper;

   static final String FILE_PATH = "/data/cong/CorpusTaggedFiles/";

    public String save() throws IOException {
        //clause_000.txt.Tag
        String fileHead="clause_";
        String fileTail=".txt.Tag";
        String fileName ="";
        for (int i = 0; i <= 160; i++) {
            if (i<10){
                fileName = fileHead+"00"+i+fileTail;
            }else if (i<99){
                fileName = fileHead+"0"+i+fileTail;
            }else {
                fileName = fileHead+i+fileTail;
            }
            System.out.println(fileName);
            String file = FILE_PATH+fileName;
            readFile(file);
        }
        return "success";
    }

    /**
     * 文件读取
     * @param file
     * @throws IOException
     */
    private void readFile(String file) throws IOException {
        File f = new File(file);
        FileInputStream inputStream = new FileInputStream(f);
        InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
        BufferedReader br = new BufferedReader(reader);
        String line = "";
        String[] arrs =null;
        while ((line= br.readLine())!=null){
            arrs=line.split("  ");
            for (String arr : arrs) {
                String[] ss = arr.split("/");
                if (ss.length==2){
                    System.out.println(ss[0]+"/"+ss[1]);
                    saveOrPass(ss);
                }
            }
        }
        br.close();
        reader.close();
        inputStream.close();
    }

    /**
     * 保存或者（已经存在该词）跳过
     * @param ss
     */
    private void saveOrPass(String[] ss) {
        Clause clause = new Clause();
        clause.setName(ss[0]);
        clause.setMark(ss[1]);
        //查询是否已经存在
        Clause one = this.clauseMapper.queryOneByNameAndMark(ss[0], ss[1]);
        if (one==null){
            int save = this.clauseMapper.save(clause);
        }
    }
}
